package com.hmall.api.config;

import com.hmall.api.client.fallback.*;
import com.hmall.common.utils.UserContext;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;

// 默认配置
public class DefaultFeignConfig {
    @Bean
    public Logger.Level feignLogger(){
        return Logger.Level.BASIC;
    }
    @Bean
    public RequestInterceptor userInfoRequestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                // 服务与服务传递数据，在服务发起方获取到用户详情
                // 之所以可以在服务发起方获取到，是因为服务的发起方是可以收到网关传过来的请求头
                // 而服务的发起可将从网关得到的数据传递给被调用方
                Long userInfo = UserContext.getUser();
                if (userInfo != null){
                    String userId = userInfo.toString();
                    requestTemplate.header("user-info",userId);
                }
            }
        };
    }
    // 各线程进行隔离的兜底
    @Bean
    public ItemClientFallbackFactory itemClientFallbackFactory(){
        return new ItemClientFallbackFactory();
    }
    @Bean
    public CartClientFallbackFactory cartClientFallbackFactory(){
        return new CartClientFallbackFactory();
    }
    @Bean
    public TradeClientFallbackFactory tradeFallbackFactory(){
        return new TradeClientFallbackFactory();
    }
    @Bean
    public UserClientFallbackFactory userClientFallbackFactory(){
        return new UserClientFallbackFactory();
    }
    @Bean
    public PayClientFallbackFactory payClientFallbackFactory(){
        return new PayClientFallbackFactory();
    }
}
